/**
 * Created by TomSean on 2017/4/20.
 */
var AccessRightManager = function ($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}

AccessRightManager.prototype = {
    init : function () {
        var _this = this;
        var fieldArray = _this.sysUtils.getBindFieldArray(_this.$parent.find('.search-panel'));
        var functionArray = [
            {fName : 'search_btn' , fs : _this.findData},
            {fName : 'reset_btn' , fs : _this.resetInfo}
        ];
        _this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        _this.sysUtils.bindDoucment(_this.models, _this.$parent, _this);
        Utils.createDataDictDropDownList({div:this.$parent.find('#timeoutBiling'), parentModelKey:BASIS.TIMEOUT_BILING.ROOT}, this);
        Utils.createDataDictDropDownList({div:this.$parent.find('#accreditType'), parentModelKey:BASIS.AUTHOR_TYPE.ROOT}, this);
        _this.initTable();
        _this.findData();
    },
    /*
     * 重置按钮
     */
    resetInfo:function(e){
        var that = $(e.target).data("that");
        that.sysUtils.setBindFieldNull(that.models.bindFieldArray);
    },
    initTable : function () {
        var _this = this;
        var columns = [
            {
                width : 30,
                headerTemplate : '<input type="checkbox" gridId="access_right_data_list" onclick="gridCheckAll(this)" />',
                template : '<input type="checkbox" name="access_right_id" value="${id}" />',
            },
            {
                width : 300,
                title : '授权编号',
                field : 'id'
            },
            {
                title : '车牌号',
                field : 'vehicleNo'
            },
            {
                title : '授权类型',
                template : '#:Utils.getModelNameByParentKey(BASIS.AUTHOR_TYPE.ROOT, accreditType)#'
            },
            {
                title : '生效时间',
                field : 'beginTime'
            },
            {
                title : '截止时间',
                field : 'endTime'
            },
            {
                title : '授权次数',
                field : 'accreditNumber'
            },
            {
                title : '授权原因',
                field : 'accreditRemark'
            },
            {
                title : '超时计费',
                template : '#:Utils.getModelNameByParentKey(BASIS.TIMEOUT_BILING.ROOT, timeoutBiling)#'
            },
            {
                title : '创建时间',
                field : 'createTime'
            },
            {
                title : '创建人',
                field : 'createUserid'
            }
        ];
        _this.sysUtils.createGird(_this.$parent.find('#access_right_data_list'), {
            selectable : 'single',
            autoSync : true,
            columnMenu : true,
            pageable : {input : true, numeric : false},
            columns : columns,
            change : function (e) {
                var selected = $.map(this.select(), function(itm) {
                    return $(itm).find('input[type=checkbox]').val();
                });
                _this.selectRowId = selected[0];
            }
        });
    },
    findData : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var grid = _this.$parent.find('#access_right_data_list').data('kendoGrid');
        var params = _this.sysUtils.getBindDocJson(_this.models.bindFieldArray);
        var dataT = {'jsonParam' : JSON.stringify(params)};
        var dataSource = _this.sysUtils.getDataSource({url : baseApiPath + 'access_right/list', data : dataT, dataType : 'odata'});
        grid.setDataSource(dataSource);
    },
    openNewWindow : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.isEdit = false;
        _this.openWindow('新增授权项目');
    },
    openEditWindow : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var id = '';
        id = _this.selectRowId;
        if (isEmpty(id)) {
            notification({title : '提示' ,message : '请选择您要修改的数据'}, 'info');
            return;
        }
        JsonpAjax(baseApiPath + 'access_right/info/'+id, undefined, 'json', function (res) {
            _this.isEdit = true;
            _this.entity = res;
            _this.openWindow('修改授权项目');
        }, true);
    },
    openWindow : function ( title ) {
        var _this = this;
        _this.editDiv = _this.sysUtils.openWindow(_this.editDiv, {
            title : title,
            height : "680px",
            width : "1040px",
            resizable : false,
            content : "views/parkLotCenter/accessRights/tempAuthorization_edit.html",
        }, true);
    },
    deleteAccess : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var ids = '';
        _this.$parent.find('input[name="access_right_id"]:checked').each(function (inx, itm) {
            ids += $(itm).val() + ',';
        });
        if (isEmpty(ids)) {
            notification({title : '提示', message : '请勾选中需要删除的数据'}, 'info');
            return;
        }
        ids = ids.substring(0, ids.length - 1);
        notification({title : '提示', message : '是否确认删除勾选信息？此操作无法撤销'}, 'confirm', {
            callback : function () {
                JsonpAjax(baseApiPath + 'access_right/delete', JSON.stringify({"ids":ids}), 'json', function ( res ) {
                    _this.findData();
                }, true);
            }
        })
    }
};

var AccessRightEdit = function ($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
AccessRightEdit.prototype = {
    init : function () {
        var _this = this;
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent);
        var functionArray = [
            {fName : 'save_info', fs : _this.saveInfo},
            {fName : 'cancel', fs : function () { $('#' + accessRightManager.editDiv).data('kendoWindow').close(); }}
        ];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.$parent, this);
        Utils.createDataDictDropDownList([
            {
                div:this.$parent.find('#timeoutBiling'),
                parentModelKey:BASIS.TIMEOUT_BILING.ROOT,
                select:Utils.getModelValueByModelKey(BASIS.TIMEOUT_BILING.CHARGE)
            },
            {
                div:this.$parent.find('#accreditType'),
                parentModelKey:BASIS.AUTHOR_TYPE.ROOT,
                select:Utils.getModelValueByModelKey(BASIS.AUTHOR_TYPE.RELEASE),
                change:function(e) {
                    console.log(e);
                    if (Utils.getModelValueByModelKey(BASIS.AUTHOR_TYPE.RELEASE) != _this.$parent.find('#accreditType').val()) {
                        _this.$parent.find('#accreditNumber').parents('.hint-text').hide();
                        _this.$parent.find('#timeoutBiling').parents('.hint-text').hide();
                    } else {
                        _this.$parent.find('#accreditNumber').parents('.hint-text').show();
                        _this.$parent.find('#timeoutBiling').parents('.hint-text').show();
                    }
                }
            }], this);
        this.$parent.find('#accreditNumber').kendoNumericTextBox({
            format: "n0",
            min: 1,
            max: 99999,
            step: 1
        });
        this.sysUtils.mvvmModel.set('accreditNumber', 1);
        this.loadInfo();
        this.loadTree();
    },
    loadInfo : function () {
        var _this = this;
        if (accessRightManager.isEdit == true && !isEmpty(accessRightManager.entity)) {
            _this.edit = true;
            _this.sysUtils.setBindFieldValue(accessRightManager.entity[0]);
            this.codeStr = accessRightManager.entity[0].accessChannelCode;
            var list = accessRightManager.entity[1];
            if (!isEmpty(list) && list.length > 0) {
                _this.$parent.find('#history-recode tbody').html('');
                for (var i = 0; i < list.length; i++) {
                    var data = list[i];
                    var tr = '';
                    tr += '<tr>';
                    tr += '<td style="text-align: center">'+data.inTime+'</td>';
                    tr += '<td style="text-align: center">'+data.inChannelCode+'</td>';
                    tr += '<td style="text-align: center">'+data.outTime+'</td>';
                    tr += '<td style="text-align: center">'+data.outChannelCode+'</td>';
                    tr += '<td style="text-align: center">'+data.chargeMoney+'</td>';
                    tr += '<td style="text-align: center">'+Utils.getModelNameByParentKey(BASIS.CHARGE_METHOD.ROOT, data.payMethod)+'</td>';
                    tr += '</tr>';
                    _this.$parent.find('#history-recode tbody').append(tr);
                }
            }


            accessRightManager.isEdit = false;
            accessRightManager.entity = undefined;
            _this.$parent.find('#vehicleNo').attr('disabled', 'disabled');
            _this.$parent.find('#accreditType').data("kendoDropDownList").enable(false);
        }
        if (Utils.getModelValueByModelKey(BASIS.AUTHOR_TYPE.RELEASE) != _this.$parent.find('#accreditType').val()) {
            _this.$parent.find('#accreditNumber').parents('.hint-text').hide();
            _this.$parent.find('#timeoutBiling').parents('.hint-text').hide();
        } else {
            _this.$parent.find('#accreditNumber').parents('.hint-text').show();
            _this.$parent.find('#timeoutBiling').parents('.hint-text').show();
        }
    },
    loadTree:function () {
        var _this = this;
        var setting = {
            view: {
                showLine: true,
                selectedMulti: false,
                dblClickExpand: false,
                showIcon: false
            },
            data: {
                simpleData: {
                    enable:true,
                    idKey: "code",
                    pIdKey: "pid",
                    rootPId: ""
                }
            },
            async: {
                enable: true,
                type:"post",
                url: baseApiPath + "traffic_permit_type/channel/tree",
            },
            check : {
                enable: true,
                autoCheckTrigger: true,
                chkStyle: "checkbox",
                chkboxType: { "Y": "ps", "N": "ps" }
            },
            callback : {
                onAsyncSuccess : function() {
                    var treeObj = $.fn.zTree.getZTreeObj("permit_tree");
                    treeObj.expandAll(true);
                    var codes = !isEmpty(_this.codeStr) ? _this.codeStr.split(',') : '';
                    if ( codes.length > 0 ){
                        for (var i = 0; i < codes.length; i++) {
                            var node = treeObj.getNodeByParam('code', codes[i], null);
                            if (undefined != node) {
                                treeObj.checkNode(node, true, true);
                            }
                        }
                    }
                }
            }
        };
        $.fn.zTree.init(this.$parent.find("#permit_tree"), setting);
    },
    pdCheck : function (nodes, codes, treeObj) {
        for (var i = 0; i < nodes.length; i++) {
            if (nodes[i].code == codes[i]) {
                treeObj.checkNode(nodes[i], true, true);
            }
            if ( nodes[i].children instanceof Array && nodes[i].children.length > 0) {
                this.pdCheck(nodes[i].children, codes, treeObj);
            }
        }
    },
    saveInfo : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        if (validityForm(_this.$parent)) {
            var treeObj = $.fn.zTree.getZTreeObj("permit_tree");
            var nodes = treeObj.getCheckedNodes(true);
            var ids = '';
            for (var i = 0; i < nodes.length; i++) {
                if ( nodes[i].type.indexOf('chn_') != -1 ){
                    ids += nodes[i].code+',';
                }
            }
            if (!isEmpty(ids)) {
                ids = ids.substring(0, ids.length - 1);
            }
            var params = _this.sysUtils.getBindDocJson();
            if (new Date(params['endTime']) < new Date(params['beginTime'])) {
                notification({'title':'错误', 'message':'结束时间不得小于起始时间！'}, 'info');
                return;
            }
            params['accessChannelCode'] = ids;
            var dataT = {'params' : params};
            JsonpAjax(baseApiPath + 'access_right/save', JSON.stringify(dataT), 'json', function (res) {
                accessRightManager.findData();
                $('#' + accessRightManager.editDiv).data('kendoWindow').close();
            }, true);
        }
    }
}